package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.LikeService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/like")
public class LikeController {
    @Autowired
    private LikeService likeService;

    @Autowired
    private UserService userService;
    @Autowired
    private MessageController messageController;
    // 点赞
    @PostMapping("/{postId}")
    public Map<String, Object> likePost(@PathVariable Long postId, HttpServletRequest request) {
        User user = userService.getCurrentUser(request);
        if (user == null) {
            return Map.of("code", 401, "message", "用户未登录");
        }
        likeService.likePost(user.getId(), postId);
        int likeCount = likeService.getLikeCount(postId);
        // 调用消息发送接口
        messageController.sendMessage(postId, "like", request);
        return Map.of("code", 200, "message", "点赞成功", "likeCount", likeCount, "isLiked", true);
    }

    // 取消点赞
    @DeleteMapping("/{postId}")
    public Map<String, Object> unlikePost(@PathVariable Long postId, HttpServletRequest request) {
        User user = userService.getCurrentUser(request);
        if (user == null) {
            return Map.of("code", 401, "message", "用户未登录");
        }
        likeService.unlikePost(user.getId(), postId);
        int likeCount = likeService.getLikeCount(postId);
        return Map.of("code", 200, "message", "取消点赞成功", "likeCount", likeCount, "isLiked", false);
    }

    // 获取点赞状态
    @GetMapping("/status/{postId}")
    public Map<String, Object> isLiked(@PathVariable Long postId, HttpServletRequest request) {
        User user = userService.getCurrentUser(request);
        if (user == null) {
            return Map.of("code", 401, "message", "用户未登录");
        }
        boolean isLiked = likeService.isLiked(user.getId(), postId);
        return Map.of("code", 200, "message", "success", "isLiked", isLiked);
    }

    // 获取点赞数
    @GetMapping("/count/{postId}")
    public Map<String, Object> getLikeCount(@PathVariable Long postId) {
        int likeCount = likeService.getLikeCount(postId);
        return Map.of("code", 200, "message", "success", "likeCount", likeCount);
    }

}